package com.gz.mylife.app;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.im.IMessage;
import com.gz.mylife.im.MessageChannel;
import com.gz.mylife.im.MessageDao;
import com.gz.mylife.im.Session;
import com.gz.mylife.im.SessionBean;
import com.gz.mylife.im.SessionDao;
import com.gz.mylife.util.PushUtils;
import com.igexin.sdk.PushConsts;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.listener.RegisterCidListener;
import com.zl.smartmall.library.listener.RegisterTagListener;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;

public class PushReceiver extends BroadcastReceiver {

	private static final String TAG = PushReceiver.class.getSimpleName();
	private int messageNotificationID = 10;
	private String title = "";//发送的通知的标题

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		CrashHandler.d(TAG, "onReceive() action=" + bundle.getInt("action"));
		switch (bundle.getInt(PushConsts.CMD_ACTION)) {

		case PushConsts.GET_MSG_DATA:// 获取透传数据
			// String appid = bundle.getString("appid");
			byte[] payload = bundle.getByteArray("payload");

			// smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
//			String taskid = bundle.getString("taskid");
//			String messageid = bundle.getString("messageid");
//			boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
//			CrashHandler.d(TAG, "第三方回执接口调用" + (result ? "成功" : "失败"));
			
			//有效的用户才接收推送
			if (payload != null && IAuth.getInstance().isUserValid()) {
				String data = new String(payload);
				CrashHandler.d(TAG, "Payload = " + data);
				Log.i("payload", "Payload = ===========" + data);
				try {
					JSONObject jsonData = new JSONObject(data);
					title = jsonData.getString("title");
					String type = jsonData.getString("content");
					String content = jsonData.getString("custom");
				    if(!jsonData.isNull("receiver_uid")){
				    	int receiverUid = Integer.parseInt(jsonData.getString("receiver_uid"));
				    	if(IAuth.getInstance().loadUserInfo().getUid() != receiverUid){
				    		//接收者不是自己, 推送目标错了?
				    		break;
				    	}
				    }
					if (type.equals(PushUtils.JTYPE_PRIVATE_LETTER)) {//类型是私信
						processMessage(context, type, content);
//					} else if (type.equals(JTYPE_CHATROOMS)) {
//						processChatMessage(context, type, content);
//					} else if (type.equals(JTYPE_FOLLOW)) {
//						processFollowNotification(context, content);
//					} else if (type.equals(JTYPE_COMMENT)) {
//						processCommentNotification(context, content);
					}else{
						if (content != null && content.length() != 0) {
							processNotification(context, type, content);
						}
						showNotification(context, content,type);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			break;
			
		case PushConsts.GET_CLIENTID:// 获取ClientID(CID)
			
			// 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
			String cid = bundle.getString("clientid");
			CrashHandler.d(TAG, "cid = " + cid);
			registerCID(cid);
			registerTAG(context);
			break;
			
		case PushConsts.THIRDPART_FEEDBACK:
			/*String appid = bundle.getString("appid");
			String taskid = bundle.getString("taskid");
			String actionid = bundle.getString("actionid");
			String result = bundle.getString("result");
			long timestamp = bundle.getLong("timestamp");

			Log.d("GetuiSdkDemo", "appid = " + appid);
			Log.d("GetuiSdkDemo", "taskid = " + taskid);
			Log.d("GetuiSdkDemo", "actionid = " + actionid);
			Log.d("GetuiSdkDemo", "result = " + result);
			Log.d("GetuiSdkDemo", "timestamp = " + timestamp);*/
			break;
			
		default:
			break;
		}
	}
	
	public boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			CrashHandler.d(TAG, "topActivity.getPackageName():" + topActivity.getPackageName());
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 广告推送
	 * @param title
	 * @param data
	 */
	private void processAdvert(String title, JSONObject data) {
//		try {
//			int discuzId = data.getInt("b");
//			int topicId = data.getInt("t");
//			String picture = data.getString("p");
//			String content = data.getString("c");
//			PreferenceModel.putInt(PreferenceModel.AD_DISCUZ_ID, discuzId);
//			PreferenceModel.putInt(PreferenceModel.AD_TOPIC_ID, topicId);
//			PreferenceModel.putString(PreferenceModel.AD_TITLE, title);
//			if (TextUtils.isEmpty(picture)) {
//				PreferenceModel.putString(PreferenceModel.AD_CONTENT, content);
//				PreferenceModel.putString(PreferenceModel.AD_PICTURE_URL, "");
//			} else {
//				PreferenceModel.putString(PreferenceModel.AD_CONTENT, "");
//				PreferenceModel.putString(PreferenceModel.AD_PICTURE_URL,
//						picture);
//			}
//		} catch (JSONException e) {
//			CrashHandler.e(e);
//		}
	}
	
	/**
	 * 私信消息
	 * 
	 * @param cxt
	 * @param type
	 * @param content
	 */
	private void processMessage(final Context cxt, final String type, final String content) {
//		JSONObject jsonObject;
//		try {
//			jsonObject = new JSONObject(content);
//			PushMessageInfo pushMessageInfo = PushMessageInfo.parse(jsonObject);
//			CrashHandler.d(TAG, "收到一条 - " + pushMessageInfo.getSenderNickname());
//		
//		} catch (JSONException e) {
//			CrashHandler.e(e);
//		}
		try {
			JSONObject data = new JSONObject(content);
			IMessage message = MessageDao.adapter4jpush(data);
			message.setDateline(System.currentTimeMillis() / 1000);
			int flage = MessageDao.judgeIsConnection(cxt, message);// flage
																	// =
																	// -1
																	// 表示消息被丢弃了
			if (flage != -1) {
				// 私信会话
				SessionBean session = SessionDao.adapter4jpush(data);

			
//				if(PreferenceModel.getInt(Define.KEY_CHATSESSION_NOTIFICATION, 0) == session.getFuid()){
//					session.setUnreadCount(0);
//				}else{
//					int unReadCount = SessionDao.getSessionUnreadCount(mContext, session);
//					session.setUnreadCount(unReadCount+1);
//				}
				
				
				if(isApplicationBroughtToBackground(cxt)){
					showNotificationBar(cxt, Define.MSG_NEW_IM_TITLE, 0,Session.class);
//					int unreadCountSms = PreferenceModel.getInt(PreferenceModel.unread_count_sms, 0);
//					PreferenceModel.putInt(
//							PreferenceModel.unread_count_sms, unreadCountSms+1);
//					
//					int unReadCount = SessionDao.getSessionUnreadCount(mContext, session);
//					session.setUnreadCount(unReadCount+1);
//					SessionDao.save(cxt, session);
				}else{
//					if(!Tools.isTopActivity(Dynamic.class,mContext)&&(!(Tools.isTopActivity(ChatSession.class, mContext)||Tools.isTopActivity(ChatSessionExp.class, mContext)))){
//						int unreadCountSms = PreferenceModel.getInt(PreferenceModel.unread_count_sms, 0);
//						PreferenceModel.putInt(
//								PreferenceModel.unread_count_sms, unreadCountSms+1);
//					}
//					int unreadCountSms = PreferenceModel.getInt(PreferenceModel.unread_count_sms, 0);
//					PreferenceModel.putInt(
//							PreferenceModel.unread_count_sms, unreadCountSms+1);
//					SessionDao.save(cxt, session);
//					MessageChannel.get().sendSession(session);
					
				}
				
				int unreadCountSms = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unreadCountSms + 1);
				
				int unReadCount = SessionDao.getSessionUnreadCount(cxt, session);
				session.setUnreadCount(unReadCount+1);
				SessionDao.save(cxt, session);
				
				MessageChannel.get().sendSession(session);
				MessageChannel.get().sendMessage(message);
				
				
			}

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	/**
	 * 广告消息 和活动通知入口
	 * 
	 * @param cxt
	 * @param title
	 * @param extras
	 */
	private void processNotification(final Context cxt, final String title,
			final String extras) {

		// n_content:"标题内容",
		// n_extras:{
		// "tp":"01", # 广告(00-09这10个号段预留给广告),00是推送贴子的广告
		// "t":"", # 专题的广告的t为空
		// "b":"论坛id", # 专题的广告只有b。这里就是专题广告的广告id
		//
		// "p":"广告图片的地址" # 广告图片地址，可以没有
		// "c":"广告正文" # 图片和广告正文二者只能有一个，当p不为空的时候，c就为空，反则亦然
		// }
		try {
			JSONObject data = new JSONObject(extras);
			String tp = data.getString("tp");
			if ("00".equals(tp)) {
				// 广告
				processAdvert(title, data);
				// } else if("02".equals(tp)){
				// // 新闻帖子广告
				// processNewsOrTopioc(title,data);
			} else if ("10".equals(tp)) {
				// 活动
				processActive(cxt, data);
			} else if ("11".equals(tp)) {
				// 版本升级通知
//				String appVersion = Tools.getAppVersionName(cxt);
//				String serverVer = data.getString("version");
//				if (UpdateManager.isVersionLow(appVersion, serverVer)) {
//					PreferenceModel.putBoolean(PreferenceModel.APP_NEW_VERSION,
//							true);
//					MessageChannel.get().sendVersion(true);
//				} else {
//					PreferenceModel.putBoolean(PreferenceModel.APP_NEW_VERSION,
//							false);
//				}
			}

		} catch (JSONException e) {
			CrashHandler.e(e);
		}
	}

	/**
	 * 活动的处理
	 * 
	 * @param cxt
	 * @param data
	 */
	private void processActive(final Context cxt, final JSONObject data) {
		// 接收到消息之后，将其存入db
//		ThreadExecutor.getInstance().execute(new Runnable() {
//			@Override
//			public void run() {
//				try {
//					String id = data.getString("id");
//					CrashHandler.d(TAG, "活动 id:" + id);
////					int discuz = PreferenceModel.getInt(
////							PreferenceModel.KEY_DISCUZ_ID, 0);
//					RequestParams params = new RequestParams();
//					params.put("ids", id);
//					params.put("packname","mylife");
//					params.put("discuz_id", "");
////					mClient.setCookieStore(Global.get().getCookie());
////					mClient.get(Define.msg_notify_get_ids, params,
////							new GetNotifyReponse(cxt));
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
////				PreferenceModel.putInt(PreferenceModel.unread_count_notify, 1);
////				PreferenceModel.putInt(
////						PreferenceModel.unread_count_notify_main, 1);
//				MessageChannel.get().sendNotify(new NotifyModel());
//				
//			}
//		});
	}

	// 进入动态通知页面
	public void showNotificationBar(Context context, String title, int tabIndex,Class myclass) {
		// look up the notification manager service
		NotificationManager nm = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		// The details of our fake message
		CharSequence appName = context.getResources().getString(
				R.string.app_name);

		Intent intent = new Intent();
		ComponentName componentName = new ComponentName(context, myclass);
		intent.setComponent(componentName);
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		intent.putExtra("tab_index", 2);
		intent.putExtra(Define.KEY_FROM_NOTIFACTION, 1);

		/*
		 * 关于通知的一些具体描述 http://blog.csdn.net/qinjuning/article/details/6915482
		 * FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉 FLAG_NO_CLEAR 该通知不能被状态栏的清除按钮给清除掉
		 * FLAG_ONGOING_EVENT 通知放置在正在运行
		 */

		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				intent,PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new Notification(R.drawable.ic_launcher,
				title, System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.setLatestEventInfo(context, appName, title, contentIntent);
		notification.defaults = Notification.DEFAULT_ALL;
		// 这里用DEFAULT_ALL进行了所有数据的默认，包括
		// 震动、声音、亮屏，还可以如下拆分

		/*
		* notification.defaults = Notification.DEFAULT_SOUND;
		* notification.defaults = Notification.DEFAULT_VIBRATE;
		* notification.defaults = Notification.DEFAULT_LIGHTS;
		*/
		
		nm.notify(messageNotificationID, notification);
		messageNotificationID++;
	}
	
	private void showNotification(Context context, String extra,String title) {
		// String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
		
		
		try {
			JSONObject data = new JSONObject(extra);
			String tp = data.getString("tp");
			if ("10".equals(tp) && IGZAddress.getInstance().getCurrentCommunityID()== data.getInt("cmid")) {
				NotificationManager nm = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				// The details of our fake message
				CharSequence appName = context.getResources().getString(
						R.string.app_name);
				
				Intent intent = new Intent();
				ComponentName componentName = new ComponentName(context, Plaza.class);
				intent.setComponent(componentName);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("page_index", 1);

				PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
						intent, PendingIntent.FLAG_UPDATE_CURRENT);
				Notification notification = new Notification(R.drawable.ic_launcher,
						title, System.currentTimeMillis());
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
				notification.setLatestEventInfo(context, appName, title, contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				nm.notify(messageNotificationID, notification);
				messageNotificationID++;
				MessageChannel.get().sendRoomMessage(new Object());
				
			} else if ("11".equals(tp)) {
				if(!PreferenceModel.getBoolean(Define.PREFERENCE_KEY_APP_NEW_VERSION, false)){
					return;
				}
				NotificationManager nm = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				// The details of our fake message
				CharSequence appName = context.getResources().getString(
						R.string.app_name);

				Intent intent = new Intent();
				ComponentName componentName = new ComponentName(context, Plaza.class);
				intent.setComponent(componentName);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("tab_index", 0);
				intent.putExtra("from_notification", true);


				PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
						intent,PendingIntent.FLAG_UPDATE_CURRENT);
				Notification notification = new Notification(R.drawable.ic_launcher,
						title, System.currentTimeMillis());
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
				notification.defaults = Notification.DEFAULT_ALL;
				notification.setLatestEventInfo(context, appName, title, contentIntent);
				if(PreferenceModel.getBoolean(Define.PREFERENCE_KEY_APP_NEW_VERSION, false)){
					nm.notify(messageNotificationID, notification);
					messageNotificationID++;
				}
			}else if ("15".equals(tp) && IGZAddress.getInstance().getCurrentCommunityID()== data.getInt("cmid")) {
				NotificationManager nm = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				// The details of our fake message
				CharSequence appName = context.getResources().getString(
						R.string.notifi_name);
				
				Intent intent = new Intent();
				ComponentName componentName = new ComponentName(context, Browser.class);
				intent.setComponent(componentName);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("url", FragmentMall.msgurl+"uid="+FragmentPersonal.mUserInfo.getUid());
				intent.putExtra("title", "消息通知");

				PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
						intent, PendingIntent.FLAG_UPDATE_CURRENT);
				Notification notification = new Notification(R.drawable.ic_launcher,
						title, System.currentTimeMillis());
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
				notification.setLatestEventInfo(context, appName, title, contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				nm.notify(messageNotificationID, notification);
				messageNotificationID++;
				MessageChannel.get().sendRoomMessage(new Object());
				
			} 
		} catch (JSONException e) {
			CrashHandler.e(e);
		}
	}
	
	
	/**
	 * 匿名状态下不允许注册推送CID, 先将推送CID保存到本地, 待用户登录后重新注册
	 * @param cid
	 */
	private void registerCID(final String cid) {
		if(IAuth.getInstance().loadUserInfo() != null) {
			IAuth.getInstance().registerCID(cid, new RegisterCidListener() {
				
				int reqCount;
				
				@Override
				public void onResponseFailed() {
					// TODO Auto-generated method stub
					if(reqCount < 5) {//失败重试5次
						reqCount++;
						IAuth.getInstance().registerCID(cid, this);
					}
				}
				
				@Override
				public void onOffline() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onNoNetWork() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onResponseSuccess() {
					// TODO Auto-generated method stub
					CrashHandler.d(TAG, "CID注册成功");
				}
			});
			
		}else {
			PreferenceModel.putString(Define.PREFERENCE_KEY_CID, cid);
		}
	}
	
	/**
	 * 匿名状态下不允许注册推送TAG
	 */
	private void registerTAG(final Context context) {
		if(IAuth.getInstance().loadUserInfo() != null) {
			IAuth.getInstance().registerTAG(PushUtils.buildTag(context), new RegisterTagListener() {
				
				int reqCount;
				
				@Override
				public void onResponseFailed() {
					// TODO Auto-generated method stub
					if(reqCount < 5) {//失败重试5次
						reqCount++;
						IAuth.getInstance().registerTAG(PushUtils.buildTag(context), this);
					}
				}
				
				@Override
				public void onOffline() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onNoNetWork() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onResponseSuccess() {
					// TODO Auto-generated method stub
					CrashHandler.d(TAG, "TAG注册成功");
				}
			});
		}
	}
}
